<?php

namespace App\Admin\Controllers;

use App\Admin\Extensions\QaVerify;
use App\Http\Controllers\Controller;
use App\Model\Message;
use App\Model\UserQa;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;

class UserQaController extends Controller
{
    use ModelForm;

    public function index()
    {
        $content = new Content();
        $content->header('用户专访管理');
        $content->body($this->grid());
        return $content;
    }

    protected function grid()
    {
        $grid = new Grid(new UserQa());
        $grid->model()->orderBy('id', 'desc');
        $grid->id('记录ID')->sortable();
        $grid->userProfile()->user_profile_id('用户ID');
        $grid->userProfile()->gender('性别')->display(function ($gender) {
            return $gender == 1 ? '男' : ($gender == 0 ? '女' : '-');
        });
        $grid->userProfile()->nick_name('昵称');
        $grid->question()->question('问题');
        $grid->answer('答案');
        $grid->flag('状态')->display(function ($data) {
            return $data == 1 ? '有效' : '无效';
        });
        //禁用导出
        $grid->disableExport();
        //禁用行选择
        $grid->disableRowSelector();
        $grid->disableCreateButton();
        $grid->filter(function ($filter) {
            $filter->expand();
            $filter->disableIdFilter();
            $filter->column(1 / 3, function ($filter) {
                $filter->equal('userProfile.user_profile_id', '用户ID');
            });
        });
        $grid->actions(function (Grid\Displayers\Actions $actions) {
            $actions->disableDelete();
            $actions->disableView();
            $actions->disableEdit();
            $actions->append(new QaVerify($actions->getKey(), $actions->row, 'qa/verify'));
        });
        return $grid;
    }

    function verify()
    {
        $id = request('id');
        $status = intval(request('status'));
        $record = UserQa::find($id);
        if (!$record) return ['ret' => -1, 'message' => '记录不存在'];
        //修改状态
        $record->update(['flag' => $status]);
        //违规操作
        if (0 == $status) {
            //站内信
            $systemMsg = "亲爱的用户：您于 {$record->created_at} 提交的专访回答存存在违规信息，审核不通过";
            Message::pushSystem($record->user_id, $systemMsg);
        }
        return ['ret' => 0, 'message' => '操作成功！'];
    }
}
